package config;

import client.handler.RpcResponseMessageHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.WriteTimeoutHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import message.RpcRequestMessage;
import org.springframework.scheduling.annotation.Async;
import protocol.MessageCodecSharable;
import protocol.ProcotolFrameDecoder;
import protocol.SequenceIdGenerator;
import protocol.Serializer;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Proxy;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author David
 */
@Slf4j
public class RpcConfig {
    static Properties properties;
    private static volatile Channel channel = null;
    private static final Object LOCK = new Object();
    static {
        try (InputStream in = RpcConfig.class.getResourceAsStream("/application.properties")) {
            properties = new Properties();
            properties.load(in);
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static int getServerPort() {
        String value = properties.getProperty("RpcServer.port");
        if(value == null) {
            return 2021;
        } else {
            return Integer.parseInt(value);
        }
    }

    public static String getPackageName() throws Exception {
        String name = properties.getProperty("RpcServer.packageName");
        if(name == null){
            throw new Exception("请添加包扫描路径");
        }else {
            return name;
        }
    }

    public static String getHost(){
        String host = properties.getProperty("RpcServer.host");
        if(host == null){
            return "localhost";
        }else {
            return host;
        }
    }

    public static Serializer.Algorithm getSerializerAlgorithm() {
        String value = properties.getProperty("RpcServer.algorithm");
        if(value == null) {
            return Serializer.Algorithm.Json;
        } else {
            return Serializer.Algorithm.valueOf(value);
        }
    }

    /**
     * 创建代理类
     */
    public static <T> T getProxyService(Class<T> serviceClass) {

        ClassLoader loader = serviceClass.getClassLoader();
        Class<?>[] interfaces = new Class[]{serviceClass};
        //                                                            sayHello  "张三"
        Object o = Proxy.newProxyInstance(loader, interfaces, (proxy, method, args) -> {

            // 1. 将方法调用转换为 消息对象
            String name = serviceClass.getName();
            int i = name.length() - 1;
            while(name.charAt(i) != '.'){
                i --;
            }
            int sequenceId = SequenceIdGenerator.nextId();
            RpcRequestMessage msg = new RpcRequestMessage(
                    sequenceId,
                    name.substring(i+1),
                    method.getName(),
                    method.getReturnType(),
                    method.getParameterTypes(),
                    args
            );
            // 2. 将消息对象发送出去
            getChannel().writeAndFlush(msg);

            // 3. 准备一个空 Promise 对象，来接收结果             指定 promise 对象异步接收结果线程
            DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
            RpcResponseMessageHandler.PROMISES.put(sequenceId, promise);

//            promise.addListener(future -> {
//                // 线程
//            });

            // 4. 等待 promise 结果
            promise.await();
            if(promise.isSuccess()) {
                // 调用正常
                return promise.getNow();
            } else {
                // 调用失败
                throw new RuntimeException(promise.cause());
            }
        });
        return (T) o;
    }

    /**
     * 典型的单例模式，channel初始化一次
     * @return 返回唯一的channel
     */
    public static Channel getChannel() {
        if (channel != null && channel.isActive()) {
            return channel;
        }
        synchronized (LOCK) {
            if (channel != null && channel.isActive()) {
                return channel;
            }
            initChannel();
            return channel;
        }
    }
    /**
     * 初始化 channel 方法
     */
    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ProcotolFrameDecoder());
                ch.pipeline().addLast("消息编解码", MESSAGE_CODEC);
                ch.pipeline().addLast("自定义", RPC_HANDLER);
            }
        });
        try {
            int port = RpcConfig.getServerPort();
            String host = RpcConfig.getHost();
            channel = bootstrap.connect(host, port).sync().channel();
            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("client error", e);
        }
    }

}